package com.edu.controller.front.order;

import com.edu.entity.Diningcar;
import com.edu.entity.Order;
import com.edu.entity.User;
import com.edu.service.diningcar.DiningCarService;
import com.edu.service.diningcar.DiningCarServiceImpl;
import com.edu.service.ordertab.OrderService;
import com.edu.service.ordertab.OrderServiceImpl;
import com.edu.utils.GetLoginUser;
import com.edu.utils.OrderSnUtil;
import com.edu.utils.ParamFormat;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigInteger;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

/**
 * @author ZCN
 * @version 1.0
 * @date 2021/11/23 17:37
 */
@WebServlet("/front/confirmorder")
public class ConfirmOrderServlet extends HttpServlet {
    private OrderService orderService = new OrderServiceImpl();
    private DiningCarService diningCarService = new DiningCarServiceImpl();
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            ParamFormat.format(req, resp);
            // 拿到购物车id
            String ids = req.getParameter("ids");

            // 获取登录用户
            User user = GetLoginUser.getUser(req);
            // 封装参数
            Order order = new Order();
            order.setUserid(user.getId());

            String ordersn = OrderSnUtil.order();
            order.setOrdersn(ordersn);

            order.setStatus(0);
            order.setCreatetime(new Timestamp(new Date().getTime()));
            order.setClosetime(new Timestamp(new Date().getTime()+15*60*1000));
            order.setPaytime(null);

            List<Diningcar> diningcars = diningCarService.selectByUserid(user.getId());
            String foodid = "";
            Integer price = 0;
            for (Diningcar diningcar : diningcars) {
                foodid += diningcar.getFoodid() + ",";
                price += diningcar.getPrice();
            }
            // 会多一个逗号
            String realfoodid = foodid.substring(0, foodid.length() - 1);
            order.setPayfoodid(realfoodid);
            order.setOrdername("菜品订单支付");
            order.setPrice(price);
            // 插入订单表（生成数据）
            BigInteger id = orderService.returnKeyAfterInsert(order);

            // 将刚插入的数据查询出来，返回给前端展示数据
            Order orderfromdb = orderService.selectByid(id);

            // 将购物车清空(状态改为已消费)
            diningCarService.updateFlagtoconsum(ids);

            req.setAttribute("order",orderfromdb);
            req.getRequestDispatcher("/front/confirmorder.jsp").forward(req,resp);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
